//
//  TYZCallPhoneTool.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/16.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "TYZCallPhoneTool.h"
#import <CallKit/CXCallObserver.h>
#import <CallKit/CXCall.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>
typedef NS_ENUM(NSUInteger, TYZPhoneStateType) {
    PhoneStateType_None = 0,
    PhoneStateType_On = 1,
    PhoneStateType_Connect = 2,
    PhoneStateType_End = 3
};

@implementation TYZCallPhoneModel
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        self.user_id = [aDecoder decodeObjectForKey:@"user_id"];
        self.activity_id = [aDecoder decodeObjectForKey:@"activity_id"];
        self.custom_id = [aDecoder decodeObjectForKey:@"custom_id"];
        self.phoneNumber = [aDecoder decodeObjectForKey:@"phoneNumber"];
        self.startTime = [aDecoder decodeObjectForKey:@"startTime"];
        self.realTime = [aDecoder decodeObjectForKey:@"realTime"];
        self.dailTime = [aDecoder decodeObjectForKey:@"dailTime"];
    }
    return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.activity_id forKey:@"activity_id"];
    [aCoder encodeObject:self.user_id forKey:@"user_id"];
    [aCoder encodeObject:self.custom_id forKey:@"custom_id"];
    [aCoder encodeObject:self.phoneNumber forKey:@"phoneNumber"];
    [aCoder encodeObject:self.startTime forKey:@"startTime"];
    [aCoder encodeObject:self.realTime forKey:@"realTime"];
    [aCoder encodeObject:self.dailTime forKey:@"dailTime"];
}
/**
 存储模型到本地（序列化）
 */
- (void)storeSelfInSendBox {
    [NSKeyedArchiver archiveRootObject:self toFile:BaseInfo.duration];
}
/**
 从本地沙盒读取模型（反序列化）
 */
+ (instancetype)readModelInSendbox {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:BaseInfo.duration];
}
/**
 删除存储的数据
 */
+ (void)deleteModelInSendBox {
    [[NSFileManager defaultManager] removeItemAtPath:BaseInfo.duration error:nil];
}
@end

API_AVAILABLE(ios(10.0))
@interface TYZCallPhoneTool ()<CXCallObserverDelegate>
/**
 *  客户的ID
 */
@property(nonatomic, copy) NSString *custom_id;
/**
 *  拨出的电话号码
 */
@property(nonatomic, copy) NSString *phoneNumber;
/**
 *  当前活动ID
 */
@property(nonatomic, copy) NSString *activity_id;
/**
 *  拨出的电话号码ID
 */
@property(nonatomic, copy) NSString *callID;
/**
 *  电话状态中心
 */
@property (nonatomic, strong) CXCallObserver *callObserver;
/**
 *  呼叫中心
 */
@property (nonatomic, strong) CTCallCenter *callCenter;
/**
 *  监听电话状态
 */
@property (nonatomic, assign) TYZPhoneStateType phoneState;
/**
 *  是否接通中
 */
@property (nonatomic, assign) BOOL isCalling;
/**
 *  开始接通时间
 */
@property (nonatomic, strong) NSDate *realDate;
/**
 *  开始拨出时间
 */
@property (nonatomic, strong) NSDate *dailDate;
/**
 *  挂断时间
 */
@property (nonatomic, strong) NSDate *endDate;
@end

@implementation TYZCallPhoneTool
- (instancetype)init {
    static dispatch_once_t onceToken;
    static TYZCallPhoneTool *instance = nil;
    WEAKSELF
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationWillTerminateNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
        weakSelf.endDate = [NSDate date];
    }];
    dispatch_once(&onceToken,^{
        instance = [super init];
        [self.callObserver setDelegate:self queue:dispatch_get_main_queue()];
        WEAKSELF
        self.callCenter.callEventHandler = ^(CTCall * call) {
            if ([call.callState isEqualToString:CTCallStateDisconnected]) {// Call has been disconnected
                NSLog(@"电话 --- 断开连接");
                if ([call.callID isEqualToString:weakSelf.callID]) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        weakSelf.endDate = [NSDate date];
                    });
                }
                weakSelf.callID = nil;
            } else if ([call.callState isEqualToString:CTCallStateConnected]) {// Call has just been connected
                NSLog(@"电话 --- 接通");
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.realDate = [NSDate date];
                });
            } else if ([call.callState isEqualToString:CTCallStateIncoming]) {// Call is incoming
                NSLog(@"电话 --- 待接通");
            } else if ([call.callState isEqualToString:CTCallStateDialing]) {// Call is Dialing
                NSLog(@"电话 --- 拨号中");
                weakSelf.callID = call.callID;
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.dailDate = [NSDate date];
                });
            } else {// Nothing is done"
                NSLog(@"电话 --- 无操作");
            }
        };
    });
    return instance;
}
- (void)setEndDate:(NSDate *)endDate {
    _endDate = endDate;
    NSInteger realTime = [endDate timeIntervalSince1970] - [self.realDate timeIntervalSince1970];
    NSInteger dailTime = [endDate timeIntervalSince1970] - [self.dailDate timeIntervalSince1970];
    if (self.callPhoneRealTime) {
        self.callPhoneRealTime(realTime);
    }
    if (self.callPhoneDialTime) {
        self.callPhoneDialTime(dailTime);
    }
    // 存储到本地
    if (realTime > 0) {
        TYZCallPhoneModel *model = [[TYZCallPhoneModel alloc] init];
        model.user_id = UserInfo.userid;
        model.custom_id = self.custom_id;
        model.phoneNumber = self.phoneNumber;
        model.activity_id = self.activity_id;
        model.startTime = self.dailDate;
        model.realTime = [NSString stringWithFormat:@"%ld", realTime];
        model.dailTime = [NSString stringWithFormat:@"%ld", dailTime];
        [model storeSelfInSendBox];
        NSLog(@"%@", model);
    }
}
/**
 打电话

 @param phoneNumber 电话号码
 @param activity_id 活动ID
 @param custom_id   客户ID
 */
- (void)callPhoneWithNumber:(NSString *)phoneNumber inActivity_id:(NSString *)activity_id custom_id:(NSString *)custom_id {
    self.phoneNumber = phoneNumber;
    self.activity_id = activity_id;
    self.custom_id = custom_id;
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneNumber];
    UIWebView *callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [[TYZSystemDialog getCurrentViewController].view addSubview:callWebview];
}
#pragma mark - CXCallObserverDelegate
- (void)callObserver:(CXCallObserver *)callObserver callChanged:(CXCall *)call  API_AVAILABLE(ios(10.0)){
    if (call.outgoing) {
        self.phoneState = PhoneStateType_None;
    }
    if (call.onHold) {
        self.phoneState = PhoneStateType_On;
    }
    if (call.hasConnected) {
        self.phoneState = PhoneStateType_Connect;
    }
    if (call.hasEnded) {
        self.phoneState = PhoneStateType_End;
    }
}
#pragma mark - getter & setter
- (CXCallObserver *)callObserver  API_AVAILABLE(ios(10.0)){
    if (_callObserver == nil) {
        _callObserver = [[CXCallObserver alloc] init];
    }
    return _callObserver;
}
- (CTCallCenter *)callCenter {
    if (_callCenter == nil) {
        _callCenter = [[CTCallCenter alloc] init];
    }
    return _callCenter;
}
- (void)setPhoneState:(TYZPhoneStateType)phoneState {
    _phoneState = phoneState;
    switch (phoneState) {
        case PhoneStateType_None:
            NSLog(@"拨打");
            break;
        case PhoneStateType_On:
            
            break;
        case PhoneStateType_Connect:
            if (self.isCalling) break;
            self.isCalling = YES;
            break;
        case PhoneStateType_End:
            self.isCalling = NO;
            break;
        default:
            break;
    }
}
- (void)setIsCalling:(BOOL)isCalling {
    _isCalling = isCalling;
    if (isCalling) {
        NSLog(@"电话接通");
    } else {
        NSLog(@"电话挂断");
    }
}
@end
